package com.recruit.servlet;

import com.recruit.entity.User;
import com.recruit.service.UserLoginAndRegistService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/****
 * author:丁文彬
 * time：2020.9.25
 */
@WebServlet(name = "UserLoginAndRegistServlet" ,urlPatterns = "/user")
public class UserLoginAndRegistServlet extends HttpServlet {
    //service层
    private UserLoginAndRegistService userLoginAndRegistService = new UserLoginAndRegistService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取操作方式
        String method = request.getParameter("method");
        //登录
        if ("login".equals(method)){
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            User user = userLoginAndRegistService.userLogin(username, password);
            if (user!=null){
                //传送user对象到前端
                request.setAttribute("user",user);
                //主页
                request.getRequestDispatcher("userMain.jsp").forward(request,response);
            }else {
                request.setAttribute("userLoginMsg","用户名和密码错误!");
                request.getRequestDispatcher("user.jsp").forward(request,response);
            }
        }else if ("register".equals(method)) {
            //获取注册数据
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String email = request.getParameter("email");
            String phone = request.getParameter("phone");
            Integer age = Integer.valueOf(request.getParameter("age"));
            //获取性别
            String[] values = request.getParameterValues("sex");
            String sex = values[0];
            //封装对象User
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            user.setEmail(email);
            user.setPhone(phone);
            user.setAge(age);
            user.setSex(sex);
            //获取service层注册服务
            int index = userLoginAndRegistService.userRegister(user);
            if (index>0){
                request.setAttribute("userRegisterMsg","注册成功，请登录!");
                request.getRequestDispatcher("user.jsp").forward(request,response);

            }else {
                request.setAttribute("userRegisterMsg","注册失败，请联系管理员!");
                request.getRequestDispatcher("user.jsp").forward(request,response);
            }
        }

    }

}
